package com.bbseguros.pesquisador.action;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bbseguros.pesquisador.bean.UserBean;
import com.bbseguros.pesquisador.dao.UserDAO;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private UserBean user;
	private String isLogin;
	private String sessionRecovery;

	private static Logger logger = Logger.getLogger(LoginAction.class);

	public String execute() throws Exception {

		String retorno = SUCCESS;
		String senhaForm = user.getSenha().trim();
		logger.debug("User: " + user.getCodigo_usuario() + " Password New: " + senhaForm);

		user = UserDAO.getInstance().selectUserByUserCode(user.getCodigo_usuario());

		if (user == null || !user.getSenha().trim().equals(senhaForm) || user.getIdPerfil() > 1) {
			logger.debug(getText("user.loginError"));
			addActionError(getText("user.loginError"));
			retorno = ERROR;
		} else {
			Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("login", "true");
			session.put("context", new Date());
			
			if(sessionRecovery!=null && sessionRecovery.equals("true")) {
				retorno = "session";
			}
		}
		return retorno;
	}

	public String logout() throws Exception {
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove("login");
		session.remove("context");
		
		return SUCCESS;
	}

	public void validate() {

		if (getUser().getCodigo_usuario() != null) {
			if (getUser().getCodigo_usuario().length() == 0) {
				addFieldError("user.usuario", getText("user.required"));
			}
		}
		if (getUser().getSenha() != null) {
			if (getUser().getSenha().length() == 0) {
				addFieldError("user.senha", getText("password.required"));
			}
		}
		setIsLogin("true");
	}

	public UserBean getUser() {
		return user;
	}

	public void setUser(UserBean user) {
		this.user = user;
	}

	public String getIsLogin() {
		return isLogin;
	}

	public void setIsLogin(String isLogin) {
		this.isLogin = isLogin;
	}

	public String getSessionRecovery() {
		return sessionRecovery;
	}

	public void setSessionRecovery(String sessionRecovery) {
		this.sessionRecovery = sessionRecovery;
	}
}
